package com.jinhu.quce.controller;

import cn.hutool.core.io.FileUtil;
import com.jinhu.quce.common.BaseResponse;
import com.jinhu.quce.common.ErrorCode;
import com.jinhu.quce.common.ResultUtils;
import com.jinhu.quce.exception.BusinessException;
import com.jinhu.quce.manager.CosManager;

import com.jinhu.quce.service.UserService;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import javax.annotation.Resource;

import com.jinhu.quce.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 *
 * @author jinhu
 * 
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        validFile(multipartFile);
        String originalFilename = multipartFile.getOriginalFilename();
        assert originalFilename != null;
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

//        file.transferTo(new File("E:\\java_file\\" + fileName));
        log.info("上传文件：{}", fileName);
        //上传到阿里云
        String url = AliOssUtil.uploadFile(fileName, multipartFile.getInputStream());
        log.info("上传成功，url={}", url);
        return ResultUtils.success(url);
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private void validFile(MultipartFile multipartFile) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (fileSize > ONE_M) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
        }
        if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }
    }
}
